package com.ebupt.migu.music.common.sms;

import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.music.common.constants.StrategyConstants;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.HttpUtils;
import com.github.mustachejava.Code;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 短信发送类
 *
 * @author zhanggk
 */
@Slf4j
@Component
public class Sender {

    /**
     * 登陆短信模板ID
     */
    public static String LOGIN_CODE = "20100001";

    /**
     * 短信审核模板ID
     */
    public static String CHECK_CODE = "20100067";

    /**
     * 短信审核模板ID
     */
    //public static String CHECK_CODE = "20100002";


    /**
     * 短信审核结果模板ID
     */
    public static String CHECK_RESULT_CODE = "20100068";

    /**
     * 短信审核结果模板ID
     */
    //public static String CHECK_RESULT_CODE = "20100003";


    /**
     * 短信审核结零时果模板ID
     */
    public static String CHECK_LS_RESULT_CODE = "20100069";


    /**
     * 短信接收成功
     */
    private static String MSG_RETURN_CODE_SUCCESS = "000000";

    // 源号码(默认为10658830, 手机终端收到消息后显示的号码), 对于有扩展子号码的需求开放
    private static String SOURCE_ADDR = "10658830";

    /**
     * 是否发送短信，0-不发送，1-发送
     */
    private static boolean isOpen;

    //大营销平台ip
    private static String MEGAMARKET_IP;

    //大营销平台接口地址
    private static String MEGAMARKET_SENDMARKETINGSMS;

    //大营销平台盐值
    private static String MEGAMARKET_SALTVALUE;

    //大营销平台渠道号
    private static String MEGAMARKET_SENDCHANNEL;

    //大营销平台接入方编码
    private static String MEGAMARKET_ACCESSCODE;

    @Value("${system.sms.open}")
    public void setIsOpen(boolean isOpen) {
        Sender.isOpen = isOpen;
    }

    @Value("${megamarket.ip}")
    public void setMegamarketIp(String megamarketIp) {
        Sender.MEGAMARKET_IP = megamarketIp;
    }

    @Value("${megamarket.sendMarketingSMS}")
    public void setMegamarketSendmarketingsms(String megamarketSendmarketingsms) {
        Sender.MEGAMARKET_SENDMARKETINGSMS = megamarketSendmarketingsms;
    }

    @Value("${megamarket.saltValue}")
    public void setMegamarketSaltvalue(String megamarketSaltvalue) {
        Sender.MEGAMARKET_SALTVALUE = megamarketSaltvalue;
    }

    @Value("${megamarket.sendChannel}")
    public void setMegamarketSendchannel(String megamarketSendchannel) {
        Sender.MEGAMARKET_SENDCHANNEL = megamarketSendchannel;
    }

    @Value("${megamarket.accessCode}")
    public void setMegamarketAccesscode(String megamarketAccesscode) {
        Sender.MEGAMARKET_ACCESSCODE = megamarketAccesscode;
    }

    /**
     * MD5加密
     *
     * @param str 加密前的字符串
     * @return 返回加密后的字符串
     */
    private static String getMD5String(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5".toUpperCase());
            byte[] digest = md.digest(str.getBytes());
            return bytesToString(digest);
        } catch (Exception e) {
            log.error("md5加密失败，错误原因：[{}]", e.getMessage());
        }
        return null;
    }

    /**
     * 转换成String
     *
     * @param data byte数组
     * @return 转换后的string
     */
    private static String bytesToString(byte[] data) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] temp = new char[data.length * 2];
        for (int i = 0; i < data.length; i++) {
            byte b = data[i];
            temp[(i * 2)] = hexDigits[(b >>> 4 & 0xF)];
            temp[(i * 2 + 1)] = hexDigits[(b & 0xF)];
        }
        return new String(temp).toUpperCase();
    }

    /**
     * 生成header 请求头（用于合法性验证）
     *
     * @return RequestHeader
     */
    private static RequestHeader getRequestHeader() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(now);
        String msgId = "2010100" + date + "00000000";
        RequestHeader rh = new RequestHeader();
        rh.setMsgId(msgId);
        rh.setDeviceId("2010");
        rh.setDevicePwd(getMD5String(msgId + "123abc!@#"));
        rh.setAccessPlatformID("100");
        return rh;
    }


    /**
     * 通用短信接口
     *
     * @param msgCode 短信模板ID,由消息下发平台统一配置分配
     * @param tel     目的手机号码,数组，可填多个
     * @param tplVars 模板中变量值(如模板中没有变量，可以为空)
     */
    public static void sendSMS(String msgCode, String[] tel, String[] tplVars) {
        Response response;
        //根据配置文件，判断是否发送短信
        if (isOpen) {
            log.info("短信模板[{}]，手机号码：[{}]，短信内容：[{}]", msgCode, tel, tplVars);
            try {
                response = new MessageSenderServiceLocator()
                        .getMessageSender()
                        .sendSmTplMessage(getRequestHeader(), SOURCE_ADDR, tel, msgCode, tplVars);
                log.info("response info:{}", response.toString());
                log.info("发送短信结果返回：code[{}], message[{}]", response.getReturnCode(), response.getDescription());
            } catch (RemoteException e) {
                log.error("短信发送失败，error[{}]", e);
            } catch (ServiceException e) {
                log.error("短信发送失败，error[{}]", e);
            }
        }
    }


    /**
     * 大营销平台短信下发
     *
     * @param tels      电话号码，多个,中间用,隔开
     * @param contentId 内容
     * @return
     */
    public static void send2MegamarketSMS(String tels, String contentId) {
        if (isOpen) {
            log.info("手机号码：[{}]，短信内容：[{}]", tels, contentId);
            //组装请求头
            Map<String, String> header = Maps.newHashMap();
            header.put("version", StrategyConstants.MEGAMARKET_VERSION);
            String sid = "TS" + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS);
            header.put("transactionId", sid);
            header.put("timestamp", DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS));
            header.put("accessCode", MEGAMARKET_ACCESSCODE);
            // 询问秘钥
            header.put("signature", getSignature(header));
            //组装请求参数
            JSONObject body = new JSONObject();
            body.put("sendChannel", MEGAMARKET_SENDCHANNEL);
            body.put("sendType", StrategyConstants.MEGAMARKET_SENDTYPE_SMS);
            body.put("receiverNo", tels);
            body.put("msgType", StrategyConstants.MEGAMARKET_MSGTYPE);
            body.put("msgContent", contentId);
            String url = MEGAMARKET_IP + MEGAMARKET_SENDMARKETINGSMS;
            JSONObject sendParams = new JSONObject();
            sendParams.put("body", body);
            sendParams.put("header", header);
            log.info(">>>>>>>>>>>>>>>请求报文:{}", sendParams.toJSONString());
            try {
                String responseString = HttpUtils.doPost(url, sendParams.toJSONString(), null);
                JSONObject response = JSONObject.parseObject(responseString);
                log.info("发送短信结果返回：手机号码:[{}], message[{}]", tels, response.toJSONString());
            } catch (Exception e) {
                log.error("短信发送失败，手机号码:[{}], error[{}]", tels, e.getMessage());
            }

        }

    }

    //拼接签名
    private static String getSignature(Map<String, String> header) {
        StringBuilder signature = new StringBuilder();
        signature.append("version").append("=").
                append(header.get("version")).append("&");
        signature.append("transactionId").append("=").
                append(header.get("transactionId")).append("&");
        signature.append("timestamp").append("=").
                append(header.get("timestamp")).append("&");
        signature.append("accessCode").append("=").
                append(header.get("accessCode"));
        signature.append(MEGAMARKET_SALTVALUE);
        return getMD5String(signature.toString()).toLowerCase();
    }
}
